import {createRouter, createWebHistory, RouteRecordRaw} from "vue-router";
import {queryMenuTree} from "@/api";
import nprogres from 'nprogress'
const globalRoutes:RouteRecordRaw[] =[
    {
        path:'/home',
        name:'home',
        component:()=>import('@/layout/default-layout.vue'),
        redirect:'dashboard/index',
        meta:{
           title:'首页'
        },
        children:[

        ]
    },
    {
        path:'/',
        name:'login',
        component:()=>import('@/views/login/index.vue'),
        meta:{
            title:'登录'
        }
    },
    {
        path:'/404',
        name:'404',
        component:()=>import('@/views/404.vue'),
        meta:{
            title:'404'
        }
    }
]
const router = createRouter({
    history:createWebHistory(),
    // @ts-ignore
    isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
    routes:[
        ...globalRoutes
    ]
})

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
const modules = import.meta.glob('@/views/**/*.vue')



const generateRouter = (menuList:any,tree:any,parentKey = [])=>{
    if (!Array.isArray(menuList)) {
        return menuList;
    }

    menuList.forEach((item:any)=>{
            item.parentKey = parentKey;
            item['meta'] = {
                    title:item.name,
                    icon:item.icon
                }
        if (item.children&&item.children.length>0){
            // @ts-ignore
            const temp = generateRouter(item.children,[],[...item.parentKey,...[item.path]]);
            item.children = temp

            tree.push(item)
        }else {
            tree.push(item)
        }
        if(item.path&&item.type==1){
            let routerObj =  {
                path:"/"+item.path,
                name:item.path.replace('/', '-'),
                meta:{
                    title:item.name,
                    icon:item.icon
                },

            }

            routerObj['component'] = modules[`/src/views/${item.path||''}.vue`]

            // @ts-ignore
            if(routerObj.component){
                // @ts-ignore
                router.addRoute('home',routerObj)
            }


        }
    })

    router.addRoute({
        path: '/:catchAll(.*)',
        component: ()=>import('@/layout/default-layout.vue'),
        redirect:"/404",
        meta:{
            title: '404'
        },
        children:[]
    })
  return tree;
}
// @ts-ignore
router.beforeEach((to, from, next) => {
    nprogres.start();
    const obj = localStorage.getItem('useSystemStore');

    // @ts-ignore
    if(globalRoutes.find(item=>to.name&&item.name===to.name)||router.isAddDynamicMenuRoutes){
        next();
    }else if(obj&&JSON.parse(obj).userInfo){
        queryMenuTree().then(res=>{
            // @ts-ignore
           const menuTree =  generateRouter(res.result.menuTree,[]);
            // @ts-ignore
            localStorage.setItem('permissionList',JSON.stringify(res.result.permissionList))
            localStorage.setItem('menuTree',JSON.stringify(menuTree))

            // @ts-ignore
            router.isAddDynamicMenuRoutes = true;

            next({...to,replace: true})
        })
    }else {
        return router.replace({name:'login'});
    }
})
router.afterEach(()=>{
    nprogres.done();
})
export default router;
